package hu.blok1.veilingsite.server;

import hu.blok1.veilingsite.client.data.AccountService;
import hu.blok1.veilingsite.shared.Address;
import hu.blok1.veilingsite.shared.Security;
import hu.blok1.veilingsite.shared.User;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class AccountServiceImpl extends RemoteServiceServlet implements
		AccountService {

	@Override
	public User logIn(User user) throws IllegalArgumentException {
		User returning = new User();
		String unhashedPassword = user.getPassword();
		user.setPassword(Security.hashPassword(user.getPassword()));
		String query = "SELECT * FROM USERS WHERE email='" + user.getEmail()
				+ "' AND password='" + user.getPassword() + "'";
		returning = GetUserObject
				.GetSingleUser(DBConnector.GetResultSet(query));
		returning.setLoggedIn();
		String queryAddress = "SELECT * FROM address WHERE id = "
				+ returning.getAddressId();
		returning.setAddress(GetUserObject.GetAddress(DBConnector
				.GetResultSet(queryAddress)));
		DBConnector.CloseAll();

		if (returning.getStatus().equals("none"))
			returning.setStatus("invalid");

		if (returning.isLoggedIn()) {
			Logger.Log("LogInSucces",
					returning.getEmail() + " : " + returning.getPassword());
		} else {
			Logger.Log("LogInFailed", user.getEmail() + " : "
					+ unhashedPassword);

		}
		return returning;
	}

	@Override
	public boolean createAccount(User _user, Address _address)
			throws IllegalArgumentException {
		boolean ret = false;
		boolean hasEmailAlready = false;

		try {
			int id_user = 0;
			int id_address = 0;
			String emailToCheck = _user.getEmail();
			String emailToQuery = "SELECT email FROM users WHERE email='" + emailToCheck + "'";
			ResultSet rsEmail = DBConnector.GetResultSet(emailToQuery);
			while(rsEmail.next()){
				hasEmailAlready = true;
			}
			rsEmail.close();
			
			if(!hasEmailAlready){
	
				ResultSet rs = DBConnector
						.GetResultSet("SELECT MAX(id) AS \"highestID\" FROM users");
				while (rs.next()) {
					id_user = rs.getInt("highestID");
					if (id_user > 0) {
						id_user++;
					} else {
						id_user++;
					}
				}
				
				rs = DBConnector
						.GetResultSet("SELECT MAX(id) AS \"highestID\" FROM address");
				while (rs.next()) {
					id_address = rs.getInt("highestID");
					if (id_address > 0) {
						id_address++;
					} else {
						id_address++;
					}
				}
				String query_address = "INSERT INTO address (id, streetname, housenumber, place, country, phonenumber, postcode) VALUES ('"
						+ id_address
						+ "', '"
						+ _address.getStreet()
						+ "', "
						+ _address.getHouseNumber()
						+ ", '"
						+ _address.getCity()
						+ "', '"
						+ _address.getCountry()
						+ "', '"
						+ _address.getPhoneNumber() 
						+ "', '"
						+ _address.getPostCode() + "')";
				rs = DBConnector.GetResultSet(query_address);
	
				String query_user = "INSERT INTO users (id, name, lastname, email, password, register_date, usertype, bankaccount, credits, status, fk_address_id) VALUES ("
						+ id_user
						+ ", '"
						+ _user.getName()
						+ "', '"
						+ _user.getLastName()
						+ "', '"
						+ _user.getEmail()
						+ "', '"
						+ Security.hashPassword(_user.getPassword())
						+ "', sysdate, 'User', '"
						+ _user.getBankAccount()
						+ "', 0, 'Active', " + id_address + ")";
				rs = DBConnector.GetResultSet(query_user);
				ret = true;
				rs.close();
			}
			
			DBConnector.CloseAll();
		} catch (SQLException se) {
			ret = false;
			System.out.println(se.getMessage());
		}

		return ret;
	}

	public boolean updateUser(User user, Address address)
			throws IllegalArgumentException {
		boolean ret = false;

		String query = "SELECT id FROM users WHERE email='" + user.getEmail()
				+ "'";
		ResultSet rs = DBConnector.GetResultSet(query);
		int id = 0;
		try {
			while (rs.next()) {
				id = rs.getInt("id");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		if (id > 0) {
			query = "UPDATE users SET name='" + user.getName()
					+ "', lastname='" + user.getLastName() + "', bankaccount='"
					+ user.getBankAccount() + "' WHERE email='"
					+ user.getEmail() + "'";
			DBConnector.SendStatement(query);
			query = "UPDATE address SET streetname='" + address.getStreet()
					+ "', housenumber='" + address.getHouseNumber()
					+ "', place='" + address.getCity() + "', country='"
					+ address.getCountry() + "', phonenumber='"
					+ address.getPhoneNumber() + "' WHERE id='"
					+ user.getAddressId() + "'";
			DBConnector.SendStatement(query);
			ret = true;
		}
		try {
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DBConnector.CloseAll();
		return ret;
	}
	
	public boolean changePassword(User userToChangePassword){
		String query = "UPDATE users SET password='" + Security.hashPassword(userToChangePassword.getPassword()) + "' WHERE email='" + userToChangePassword.getEmail() + "'";
		DBConnector.SendStatement(query);
		DBConnector.CloseAll();
		return true;
	}
}